package com.ruicar.afs.cloud.afscase.mq.receiver.processor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.autoaudit.loan.StepParam;
import com.ruicar.afs.cloud.afscase.autoaudit.util.StepUtil;
import com.ruicar.afs.cloud.afscase.cargpsmanage.entity.CarGpsApply;
import com.ruicar.afs.cloud.afscase.cargpsmanage.service.CarGpsApplyService;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.*;
import com.ruicar.afs.cloud.afscase.infomanagement.service.*;
import com.ruicar.afs.cloud.afscase.loanapprove.entity.AddedFinancingItems;
import com.ruicar.afs.cloud.afscase.loanapprove.entity.CarInsuranceInfo;
import com.ruicar.afs.cloud.afscase.loanapprove.entity.CarInvoiceInfo;
import com.ruicar.afs.cloud.afscase.loanapprove.entity.LoanBankCardInfo;
import com.ruicar.afs.cloud.afscase.loanapprove.service.AddedFinancingItemsService;
import com.ruicar.afs.cloud.afscase.loanapprove.service.CarInsuranceInfoService;
import com.ruicar.afs.cloud.afscase.loanapprove.service.CarInvoiceInfoService;
import com.ruicar.afs.cloud.afscase.loanapprove.service.LoanBankCardInfoService;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.service.ApproveLoanInfoService;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.vo.CaseContractLogInfo;
import com.ruicar.afs.cloud.afscase.mq.entity.CaseMqAcceptRecord;
import com.ruicar.afs.cloud.afscase.mq.entity.CompareEntity;
import com.ruicar.afs.cloud.afscase.mq.service.CaseMqAcceptRecordService;
import com.ruicar.afs.cloud.afscase.mq.service.CaseMqCompareInfoService;
import com.ruicar.afs.cloud.afscase.step.entity.CaseStepParam;
import com.ruicar.afs.cloud.afscase.step.service.CaseStepParamService;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.common.core.auditlog.service.AuditLogService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.*;
import com.ruicar.afs.cloud.common.modules.enums.OprTypeEnum;
import com.ruicar.afs.cloud.common.mq.rabbit.listener.AfsMqBizProcessor;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>Description：放款申请MQ消息接收处理类</p>
 * @author xueyu.ma
 * @createDate 2020-6-16
 * @version 1.0
 * */
@AllArgsConstructor
@Slf4j
@Component
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit",name="enable")
public class LoanApplyProcessor implements AfsMqBizProcessor<LoanApplySubmitInfo> {

    private final CaseBaseInfoService caseBaseInfoService;
    private final CaseCustInfoService caseCustInfoService;
    private final CaseContractInfoService caseContractInfoService;
    private final CaseCarInfoService caseCarInfoService;
    private final CarInvoiceInfoService carInvoiceInfoService;
    private final CarGpsApplyService carGpsApplyService;
    private final CarInsuranceInfoService carInsuranceInfoService;
    private final LoanBankCardInfoService loanBankCardInfoService;
    private final CaseCustHistoryService caseCustHistoryService;
    private final AddedFinancingItemsService addedFinancingItemsService;
    private ApproveLoanInfoService approveLoanInfoService;
    private ComAttachmentFileService comAttachmentFileService;
    private CaseStepParamService caseStepParamService;
    private CaseMqCompareInfoService caseMqCompareInfoService;
    private CaseMqAcceptRecordService caseMqAcceptRecordService;
    private AuditLogService auditLogService;
    private ApplyCostDetailsService applyCostDetailsService;
    private CaseChannelInfoService caseChannelInfoService;
    private ChannelBaseInfoService channelBaseInfoService;

    @Override
    public boolean processMessage(LoanApplySubmitInfo entity) throws Exception {
        String applyNo=entity.getApplyNo();
        CaseContractLogInfo logInfo= new CaseContractLogInfo();
        String contractNo=entity.getContractNo();
        String processType=entity.getProcessType();
        WorkFlowDTO workFlowDTO=entity.getWorkFlowDTO()==null?new WorkFlowDTO():entity.getWorkFlowDTO();
        CaseMqAcceptRecord caseMqAcceptRecord=new CaseMqAcceptRecord();
        caseMqAcceptRecord.setApplyNo(applyNo);
        caseMqAcceptRecord.setContractNo(contractNo);
        caseMqAcceptRecord.setBodyContent(JSONObject.toJSONString(entity));
        caseMqAcceptRecord.setVersion(workFlowDTO.getTaskId()==null?"0":workFlowDTO.getTaskId());
        caseMqAcceptRecord.setSourceCode(AfsEnumUtil.key(MqTransCode.AFS_POS_APPLY_CASE_CTM_NEW_LOAN));
        caseMqAcceptRecordService.save(caseMqAcceptRecord);
        logInfo.setApplyNo(applyNo);
        logInfo.setContractNo(contractNo);
        logInfo.setResult(ResultBooleanEnum.TRUE.getCode());
        Throwable throwable = null;
        try{
            if(processType.equals(LoanProcessTypeEnum.GENERAL_LOAN.getCode())){
                this.ConLoanApplylistenerQueue(entity,caseMqAcceptRecord);
            }
        }catch (Throwable e){
            throwable = e;
            logInfo.setResult(ResultBooleanEnum.FALSE.getCode());
            log.info("异常原因：{}",e.getMessage());
        }
        approveLoanInfoService.loanApplyResult(logInfo);
        log.info("MQ日志保存成功-结果：{}",logInfo.getResult());
        log.info("报文信息：{}",entity.toString());
        if(ResultBooleanEnum.FALSE.getCode().equals(logInfo.getResult())){
            throw new AfsBaseException("","保存失败!",throwable);
        }
        // 自动审核部分
        if(ResultBooleanEnum.TRUE.getCode().equals(logInfo.getResult())){
            StepParam param = StepParam.builder().applyNo(applyNo).contractNo(contractNo).build();
            if(processType.equals(LoanProcessTypeEnum.GENERAL_LOAN.getCode())
                    && OprTypeEnum.OPRUPDATE.getCode().equals(entity.getOprType())) {
                param.setTaskId(workFlowDTO.getTaskId());
            }
            CaseStepParam caseStepParam = caseStepParamService.getLast(applyNo,StepSceneEnum.LOAN);
            caseStepParam.setContractNo(contractNo);
            caseStepParam.setApplyNo(applyNo);
            caseStepParam.setTaskId(param.getTaskId());
            caseStepParam.setScene(StepSceneEnum.LOAN);
            caseStepParamService.saveOrUpdate(caseStepParam);
            StepUtil.prevSteps(param);
        }
        return true;
    }

    @Override
    public MqTransCode getCode() {
        return MqTransCode.AFS_POS_APPLY_CASE_CTM_NEW_LOAN;
    }

    @Transactional(rollbackFor = Exception.class)
    public void ConLoanApplylistenerQueue(LoanApplySubmitInfo loanApplySubmitInfo,CaseMqAcceptRecord caseMqAcceptRecord)throws Exception {
        try {
            log.info("接收放款申请信息："+JSON.toJSONString(loanApplySubmitInfo));
            CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                    .eq(CaseBaseInfo::getApplyNo,loanApplySubmitInfo.getApplyNo()));
            if(!ObjectUtils.isEmpty(caseBaseInfo)){
                CaseContractInfoDTO contractInfoDTO=loanApplySubmitInfo.getCaseContractInfoDto();
                if(!ObjectUtils.isEmpty(contractInfoDTO)){
                    parseCaseContractInfoDTO(contractInfoDTO,caseBaseInfo,caseMqAcceptRecord);
                }else{
                    log.info("申请编号：{}=>合同信息表为空，MQ处理信息结束……",loanApplySubmitInfo.getApplyNo());
                    throw new IllegalArgumentException("输入合同信息表为空");
                }
            }else{
                log.error("申请编号：{}=>主表不存在……",loanApplySubmitInfo.getApplyNo());
                throw new IllegalArgumentException("基础表信息为空");
            }
        }catch (Exception e){
            log.error("申请编号：{}=>放款申请信息保存失败",loanApplySubmitInfo.getApplyNo(),e);
            log.error(e.getMessage());
            throw e;
        }
        log.info("当前线程名称：{}，状态为：{}",Thread.currentThread().getName(),Thread.currentThread().getState());
    }
    private ResultDTO parseCaseContractInfoDTO(CaseContractInfoDTO caseContractInfoDTO, CaseBaseInfo caseBaseInfo,CaseMqAcceptRecord caseMqAcceptRecord){
        String contractNo=caseContractInfoDTO.getContractNo();
        String applyNo=caseContractInfoDTO.getApplyNo();
        CaseContractInfo caseContractInfo=caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda().eq(CaseContractInfo::getContractNo,contractNo));
        CaseContractInfo original=caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda().eq(CaseContractInfo::getContractNo,contractNo));
        if(ObjectUtils.isEmpty(caseContractInfo)) {
            caseContractInfo=new CaseContractInfo();
            BeanUtil.copyProperties(caseContractInfoDTO,caseContractInfo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

            /**更新证件有效期*/
            parseCaseCustInfoList(caseContractInfoDTO.getCertificateInfoDTOList(),contractNo,applyNo,caseMqAcceptRecord);
            /**更新客户信息变更历史表*/
            parseCaseCustHistoryList(caseContractInfoDTO.getCaseCustHistoryDTOList(),contractNo,applyNo);
            /**更新银行卡信息*/
            parseLoanBankCardInfo(caseContractInfoDTO.getLoanBankCardInfoDto(),contractNo,applyNo,caseMqAcceptRecord);
            /**更新车辆信息*/
            parseCaseCarInfoList(caseContractInfoDTO.getCarInfoDtoList(),contractNo,applyNo,caseMqAcceptRecord);
            /**保存影像件信息*/
            parseAttachmentFileList(caseContractInfoDTO.getAttachmentDtoList(),contractNo,applyNo);
            /**获取合作商信息*/
            CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
                    .eq(CaseChannelInfo::getApplyNo,applyNo));
            if(!ObjectUtils.isEmpty(caseChannelInfo) && StringUtils.isNotBlank(caseChannelInfo.getDealerNo())){
                ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda()
                    .eq(ChannelBaseInfo::getChannelCode,caseChannelInfo.getDealerNo()));
                if(!ObjectUtils.isEmpty(channelBaseInfo)){
                    caseContractInfo.setChannelBelong(channelBaseInfo.getChannelBelong());
                    caseContractInfo.setDealerName(channelBaseInfo.getChannelFullName());
                    caseContractInfo.setChannelType(channelBaseInfo.getChannelType());
                    caseContractInfo.setDealerNo(channelBaseInfo.getChannelCode());
                }
            }
            caseContractInfo.setPriority(PriorityEnum.ORDINARY.getCode());
            caseContractInfo.setBusinessType(caseBaseInfo.getBusinessType());
            caseContractInfo.setProductId(caseBaseInfo.getProductId());
            caseContractInfo.setProductName(caseBaseInfo.getProductName());
            caseContractInfo.setIsTop(WhetherEnum.NO.getCode());
            caseContractInfo.setIsLock(WhetherEnum.NO.getCode());
            caseContractInfo.setLockDegree(LockDegreeEnum.NORMAL.getValue());
            caseContractInfo.setMortContractNo(contractNo);
            //放款首次提交日期
            caseContractInfo.setLendingFirstDate(new Date());
            //进入放款申请阶段
            caseContractInfo.setBusinessStage(BusinessStageEnum.LOAN_APPLY.getCode());
            //放款审核状态（内部状态）->放款待提交
            caseContractInfo.setApplyStatus(ApplyStatusEnum.LOAN_WAIT_SUBMIT.getState());
            caseContractInfo.setContractStatus(ContractStatusEnum.create);
            //报单员信息
            caseContractInfo.setUserRealName(caseContractInfoDTO.getUserRealName());
            caseContractInfo.setPhone(caseContractInfoDTO.getPhone());
            caseContractInfoService.save(caseContractInfo);
            log.info("合同号码：{}=>已新增合同数据", contractNo);
        }else{
            boolean isEdit = (caseContractInfo.getContractStatus().equals(ContractStatusEnum.approve) && caseContractInfo.getApplyStatus().equals(ApplyStatusEnum.LOAN_RETURN.getState()))
                    ||caseContractInfo.getApplyStatus().equals(ApplyStatusEnum.LOAN_WAIT_SUBMIT.getState());
            if (isEdit) {
                /**更新合同信息*/
                caseContractInfo.setLendingMode(caseContractInfoDTO.getLendingMode());
                caseContractInfo.setWitnessId(caseContractInfoDTO.getWitnessId());
                caseContractInfo.setUserRealName(caseContractInfoDTO.getUserRealName());
                caseContractInfo.setPhone(caseContractInfoDTO.getPhone());
                CaseContractInfo target =caseContractInfo;
                caseContractInfoService.updateById(caseContractInfo);
                caseMqCompareInfoService.saveInfo(CompareEntity.builder()
                        .acceptId(caseMqAcceptRecord.getId())
                        .applyNo(applyNo)
                        .contractNo(contractNo)
                        .entityClass("CaseContractInfo")
                        .original(original)
                        .target(target)
                        .version(caseMqAcceptRecord.getVersion())
                        .dataId(String.valueOf(target.getId()))
                        .build());
                /**更新证件有效期*/
                parseCaseCustInfoList(caseContractInfoDTO.getCertificateInfoDTOList(),contractNo,applyNo,caseMqAcceptRecord);
                /**更新客户信息变更历史表*/
                parseCaseCustHistoryList(caseContractInfoDTO.getCaseCustHistoryDTOList(),contractNo,applyNo);
                /**更新银行卡信息*/
                parseLoanBankCardInfo(caseContractInfoDTO.getLoanBankCardInfoDto(),contractNo,applyNo,caseMqAcceptRecord);
                /**更新车辆信息*/
                parseCaseCarInfoList(caseContractInfoDTO.getCarInfoDtoList(),contractNo,applyNo,caseMqAcceptRecord);
                /**保存影像件信息*/
                parseAttachmentFileList(caseContractInfoDTO.getAttachmentDtoList(),contractNo,applyNo);
                log.info("合同号码：{}=>已修改合同数据为预处理状态", contractNo);
            } else {
                log.info("合同号码：{}=>已发起流程或者已审核结束，跳过修改", contractNo);
            }
        }
        return null;
    }

    /**解析更新客户证件更新信息*/
    private ResultDTO parseCaseCustInfoList(ArrayList<CertificateInfoDTO >  certificateInfoDTOList,String  contractNo,String applyNo,CaseMqAcceptRecord caseMqAcceptRecord){
        if(!CollectionUtils.isEmpty(certificateInfoDTOList)){
            for (CertificateInfoDTO certificateInfoDTO :certificateInfoDTOList){
                CaseCustInfo caseCustInfo=caseCustInfoService.getOne(Wrappers.<CaseCustInfo>query().lambda()
                        .eq(CaseCustInfo::getApplyNo,applyNo)
                        .eq(CaseCustInfo::getCustRole, certificateInfoDTO.getCustRole())
                        .eq(CaseCustInfo::getCertNo, certificateInfoDTO.getCertNo()));
                /**mq留痕*/
                CaseCustInfo original=caseCustInfoService.getOne(Wrappers.<CaseCustInfo>query().lambda()
                        .eq(CaseCustInfo::getApplyNo,applyNo)
                        .eq(CaseCustInfo::getCustRole, certificateInfoDTO.getCustRole())
                        .eq(CaseCustInfo::getCertNo, certificateInfoDTO.getCertNo()));
                if(!ObjectUtils.isEmpty(caseCustInfo)){
                   String isLongTerm=certificateInfoDTO.getIsLongTerm();
                   if(isLongTerm.equals(AfsEnumUtil.key(WhetherEnum.YES))){
                       caseCustInfo.setIsLongTerm(isLongTerm);
                   }else{
                       caseCustInfo.setIsLongTerm(isLongTerm);
                       caseCustInfo.setCertEndDate(DateUtil.parseDate(certificateInfoDTO.getCertEndDate()));
                   }
                    CaseCustInfo target=caseCustInfo;
                    caseMqCompareInfoService.saveInfo(CompareEntity.builder()
                            .acceptId(caseMqAcceptRecord.getId())
                            .applyNo(applyNo)
                            .contractNo(contractNo)
                            .entityClass("CaseCustInfo")
                            .original(original)
                            .target(target)
                            .version(caseMqAcceptRecord.getVersion())
                            .dataId(String.valueOf(target.getId()))
                            .build());
                    /*auditLogService.saveAuditLog(AuditLogWrapper.builder()
                            .oldObject(original)
                            .newObject(target)
                            .changeReason("return")
                            .currentUserName("system")
                            .changeIndex(caseMqAcceptRecord.getId().toString())
                            .build());*/
                    caseCustInfoService.updateById(caseCustInfo);
                    log.info("申请编号：{}=>合同号码：{}=>客户=>{}：证件信息更新成功",applyNo, contractNo,certificateInfoDTO.getCertNo());
                }else{
                    log.error("申请编号：{}=>合同号码：{}=>客户=>{}：未找到相应客户信息",applyNo, contractNo,certificateInfoDTO.getCertNo());
                    throw new IllegalArgumentException("客户信息为空");
                }
            }
        }else{
            log.error("申请编号：{}=>合同号码：{}=>客户证件信息集合为空！",applyNo, contractNo);
            throw new IllegalArgumentException("输入证件详细信息集合为空");
        }
        return null;
    }

    /**解析客户变更历史信息*/
    private ResultDTO parseCaseCustHistoryList(ArrayList<CaseCustHistoryDTO >  caseCustHistoryDTOList,String  contractNo,String applyNo){
        if(!CollectionUtils.isEmpty(caseCustHistoryDTOList)){
            for (CaseCustHistoryDTO caseCustHistoryDTO :caseCustHistoryDTOList){
                CaseCustHistory caseCustHistory=new CaseCustHistory();
                BeanUtil.copyProperties(caseCustHistoryDTO, caseCustHistory, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                log.info("申请编号：{}=>合同号码：{}=>客户=>{}：客户信息历史表成功",applyNo, contractNo,caseCustHistoryDTO.getCertNo());
                caseCustHistoryService.saveOrUpdate(caseCustHistory);
            }
        }else{
            log.info("申请编号：{}=>合同号码：{}=>客户信息历史表集合为空，跳过更新！",applyNo, contractNo);
        }
        return null;
    }

    /**解析车辆信息*/
    private ResultDTO parseCaseCarInfoList(ArrayList<CarInfoDTO> CarInfoDtoList, String  contractNo, String applyNo,CaseMqAcceptRecord caseMqAcceptRecord){
        CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                .eq(CaseBaseInfo::getApplyNo,applyNo));
        if(!CollectionUtils.isEmpty(CarInfoDtoList)){
            for(CarInfoDTO carInfoDTO : CarInfoDtoList) {
                Long carId = carInfoDTO.getCarId();
                List<FinCostDetails> finCostDetails =applyCostDetailsService.list(Wrappers.<FinCostDetails>lambdaQuery().eq(FinCostDetails::getApplyNo,applyNo));
                finCostDetails.forEach(finCostDetail -> {
                    finCostDetail.setCarId(carId);
                    applyCostDetailsService.updateById(finCostDetail);
                });
                CaseCarInfo caseCarInfo = caseCarInfoService.getById(carId);
                CaseCarInfo original=caseCarInfoService.getById(carId);
                if (!ObjectUtils.isEmpty(caseCarInfo)){
                    if (AffiliatedWayEnum.PERSONAL_AFFILIATED.getCode().equals(caseBaseInfo.getAffiliatedWay())) {
                        //个体工商户名称
                        caseCarInfo.setIndBusinessName(carInfoDTO.getAffiliatedName());
                        //统一社会信用代码
                        caseCarInfo.setIndBusinessUsci(carInfoDTO.getSocUniCrtCode());
                    }
                    //合同号码
                    caseCarInfo.setContractNo(contractNo);
                    //VIN号码
                    caseCarInfo.setCarVin(carInfoDTO.getCarVin());
                    //发动机号
                    caseCarInfo.setEngineNo(carInfoDTO.getEngineNo());
                    //车辆型号
                    caseCarInfo.setFullModelNum(carInfoDTO.getFullModelNum());
                    //车辆颜色
                    caseCarInfo.setCarColor(carInfoDTO.getCarColor());
                    //车牌号码
                    caseCarInfo.setLicensePlate(carInfoDTO.getLicensePlate());
                    CaseCarInfo target=caseCarInfo;

                    /**车辆信息只在退回合作商重新提交之后，才比对差异信息*/
                    CaseContractInfo caseContractInfo=caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaQuery().eq(CaseContractInfo::getContractNo,contractNo));
                    if(!ObjectUtils.isEmpty(caseContractInfo)&&caseContractInfo.getApplyStatus().equals(ApplyStatusEnum.LOAN_RETURN.getState())){
                        caseMqCompareInfoService.saveInfo(CompareEntity.builder()
                                .acceptId(caseMqAcceptRecord.getId())
                                .applyNo(applyNo)
                                .contractNo(contractNo)
                                .entityClass("CaseCarInfo")
                                .original(original)
                                .target(target)
                                .version(caseMqAcceptRecord.getVersion())
                                .dataId(String.valueOf(target.getId()))
                                .build());
                    /*auditLogService.saveAuditLog(AuditLogWrapper.builder()
                            .oldObject(original)
                            .newObject(target)
                            .changeReason("return")
                            .currentUserName("system")
                            .changeIndex(caseMqAcceptRecord.getId().toString())
                            .build());*/
                    }
                    caseCarInfoService.updateById(caseCarInfo);
                    log.info("车辆编号：{}=>更新车辆信息成功！",carId);
                }else{
                    log.error("车辆编号：{}=>未找到相关的车辆信息！",carId);
                    throw new IllegalArgumentException("车辆信息为空");
                }
                /**保存发票信息*/
                parseCarInvoiceInfo(carInfoDTO.getCarInvoiceInfoDTO(),carId,contractNo,applyNo,caseMqAcceptRecord);
                /**保存保险信息*/
                parseCarInsuranceInfoList(carInfoDTO.getCarInsuranceInfoDtoList(),carId,contractNo,applyNo,caseMqAcceptRecord);
                /**保存增融信息*/
                parseAddedFinancingItemsList(carInfoDTO.getAddedFinancingItemsDTOList(), carId, contractNo, applyNo,caseMqAcceptRecord);
                /**保存GPS申请信息*/
                parseCarGpsApply(carInfoDTO);
            }
        }else{
            log.error("申请编号：{}=>合同号码：{}=>车辆信息集合为空！",applyNo, contractNo);
            throw new IllegalArgumentException("输入车辆信息集合为空");
        }
        return null;
    }

    /**解析车辆发票信息*/
    private CarInvoiceInfo parseCarInvoiceInfo(CarInvoiceInfoDTO carInvoiceInfoDTO,Long carId,String contractNo,String applyNo,CaseMqAcceptRecord caseMqAcceptRecord){
        if(!ObjectUtils.isEmpty(carInvoiceInfoDTO)) {
            CarInvoiceInfo carInvoiceInfo = carInvoiceInfoService.getOne(Wrappers.<CarInvoiceInfo>query().lambda()
                    .eq(CarInvoiceInfo::getApplyNo, applyNo)
                    .eq(CarInvoiceInfo::getContractNo, contractNo)
                    .eq(CarInvoiceInfo::getCarId, carId));
            CarInvoiceInfo original= carInvoiceInfoService.getOne(Wrappers.<CarInvoiceInfo>query().lambda()
                    .eq(CarInvoiceInfo::getApplyNo, applyNo)
                    .eq(CarInvoiceInfo::getContractNo, contractNo)
                    .eq(CarInvoiceInfo::getCarId, carId));

            if (ObjectUtils.isEmpty(carInvoiceInfo)) {
                carInvoiceInfo = new CarInvoiceInfo();
            }
            BeanUtil.copyProperties(carInvoiceInfoDTO, carInvoiceInfo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            carInvoiceInfo.setContractNo(contractNo);
            carInvoiceInfo.setCarId(carId);

            CarInvoiceInfo target=carInvoiceInfo;
            caseMqCompareInfoService.saveInfo(CompareEntity.builder()
                    .acceptId(caseMqAcceptRecord.getId())
                    .applyNo(applyNo)
                    .contractNo(contractNo)
                    .entityClass("CarInvoiceInfo")
                    .original(original)
                    .target(target)
                    .version(caseMqAcceptRecord.getVersion())
                    .dataId(String.valueOf(target.getId()))
                    .build());
            carInvoiceInfoService.saveOrUpdate(carInvoiceInfo);
            log.info("申请编号：{}=>合同号码：{}=>车辆信息{}=>发票信息保存成功！", applyNo, contractNo, carId);
        }else{
            log.error("申请编号：{}=>合同号码：{}=>输入发票信息为空！",applyNo, contractNo);
        }
        return null;
    }

    /**解析车辆保险信息*/
    private ArrayList<CarInsuranceInfo> parseCarInsuranceInfoList(ArrayList<CarInsuranceInfoDTO> CarInsuranceInfoDtoList,Long carId,String contractNo,String applyNo,CaseMqAcceptRecord caseMqAcceptRecord){
        if(!CollectionUtils.isEmpty(CarInsuranceInfoDtoList)){
            for (CarInsuranceInfoDTO carInsuranceInfoDTO : CarInsuranceInfoDtoList){
                CarInsuranceInfo carInsuranceInfo = carInsuranceInfoService.getOne(Wrappers.<CarInsuranceInfo>query().lambda()
                        .eq(CarInsuranceInfo::getApplyNo,applyNo)
                        .eq(CarInsuranceInfo::getContractNo,contractNo)
                        .eq(CarInsuranceInfo::getCarId,carId)
                        .eq(CarInsuranceInfo::getInsuranceType,carInsuranceInfoDTO.getInsuranceType()));
                CarInsuranceInfo original = carInsuranceInfoService.getOne(Wrappers.<CarInsuranceInfo>query().lambda()
                        .eq(CarInsuranceInfo::getApplyNo,applyNo)
                        .eq(CarInsuranceInfo::getContractNo,contractNo)
                        .eq(CarInsuranceInfo::getCarId,carId)
                        .eq(CarInsuranceInfo::getInsuranceType,carInsuranceInfoDTO.getInsuranceType()));
                if(ObjectUtils.isEmpty(carInsuranceInfo)){
                    carInsuranceInfo = new CarInsuranceInfo();
                }
                BeanUtil.copyProperties(carInsuranceInfoDTO,carInsuranceInfo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                carInsuranceInfo.setContractNo(contractNo);
                carInsuranceInfo.setCarId(carId);
                CarInsuranceInfo target=carInsuranceInfo;
                caseMqCompareInfoService.saveInfo(CompareEntity.builder()
                        .acceptId(caseMqAcceptRecord.getId())
                        .applyNo(applyNo)
                        .contractNo(contractNo)
                        .entityClass("CarInsuranceInfo")
                        .original(original)
                        .target(target)
                        .version(caseMqAcceptRecord.getVersion())
                        .dataId(String.valueOf(target.getId()))
                        .build());

                carInsuranceInfoService.saveOrUpdate(carInsuranceInfo);
                log.info("申请编号：{}=>合同号码：{}=>车辆编号：{}=>保险类型{}=>保险信息保存成功！",applyNo, contractNo, carId,carInsuranceInfoDTO.getInsuranceType());
            }
        }else{
            log.error("申请编号：{}=>合同号码：{}=>车辆编号：{}=>输入保险信息集合为空！",applyNo, contractNo, carId);
        }
        return null;
    }
    /**解析增融信息*/
    private ArrayList<AddedFinancingItems> parseAddedFinancingItemsList(ArrayList<AddedFinancingItemsDTO> addedFinancingItemsDtoList,Long carId,String contractNo,String applyNo,CaseMqAcceptRecord caseMqAcceptRecord){
        if(!CollectionUtils.isEmpty(addedFinancingItemsDtoList)){
            addedFinancingItemsDtoList.forEach(addedFinancingItemsDTO ->{
                AddedFinancingItems addedFinancingItems=addedFinancingItemsService.getOne(Wrappers.<AddedFinancingItems>query().lambda()
                        .eq(AddedFinancingItems::getApplyNo,applyNo)
                        .eq(AddedFinancingItems::getCarId,carId)
                        .eq(AddedFinancingItems::getId,addedFinancingItemsDTO.getId())
                        .eq(AddedFinancingItems::getFinanceItemCode, addedFinancingItemsDTO.getFinanceItemCode()));
                AddedFinancingItems original=addedFinancingItemsService.getOne(Wrappers.<AddedFinancingItems>query().lambda()
                        .eq(AddedFinancingItems::getApplyNo,applyNo)
                        .eq(AddedFinancingItems::getCarId,carId)
                        .eq(AddedFinancingItems::getId,addedFinancingItemsDTO.getId())
                        .eq(AddedFinancingItems::getFinanceItemCode, addedFinancingItemsDTO.getFinanceItemCode()));
                if(ObjectUtils.isEmpty(addedFinancingItems)){
                    addedFinancingItems = new AddedFinancingItems();
                }
                addedFinancingItems.setFinanceItemCode(addedFinancingItemsDTO.getFinanceItemCode());
                addedFinancingItems.setAddFinanceAmt(addedFinancingItemsDTO.getFinanceItemAmt());
                addedFinancingItems.setFinanceItemName(addedFinancingItemsDTO.getFinanceItemName());
                addedFinancingItems.setUpperId(addedFinancingItemsDTO.getParentItemId());
                addedFinancingItems.setId(addedFinancingItemsDTO.getId());
                addedFinancingItems.setUpdateBy(addedFinancingItemsDTO.getUpdateBy());
                addedFinancingItems.setUpdateTime(addedFinancingItemsDTO.getUpdateTime());
                addedFinancingItems.setCreateBy(addedFinancingItemsDTO.getCreateBy());
                addedFinancingItems.setCreateTime(addedFinancingItemsDTO.getCreateTime());
                addedFinancingItems.setDelFlag(addedFinancingItemsDTO.getDelFlag());
                addedFinancingItems.setApplyNo(applyNo);
                addedFinancingItems.setContractNo(contractNo);
                addedFinancingItems.setCarId(carId);
                AddedFinancingItems target=addedFinancingItems;
                caseMqCompareInfoService.saveInfo(CompareEntity.builder()
                        .acceptId(caseMqAcceptRecord.getId())
                        .applyNo(applyNo)
                        .contractNo(contractNo)
                        .entityClass("AddedFinancingItems")
                        .original(original)
                        .target(target)
                        .version(caseMqAcceptRecord.getVersion())
                        .dataId(String.valueOf(target.getId()))
                        .build());
                addedFinancingItemsService.saveOrUpdate(addedFinancingItems);
                log.info("申请编号：{}=>合同号码：{}=>车辆编号：{}=>增融项类型{}=>增融信息保存成功！",applyNo, contractNo, carId,addedFinancingItemsDTO.getFinanceItemCode());
            });
        }
        return null;
    }

    /**
     * @Description 解析GPS申请信息
     * @Author yk.Li
     * @Date 2020/08/10
     */
    private CarGpsApply parseCarGpsApply(CarInfoDTO carInfoDTO){
        if(!ObjectUtils.isEmpty(carInfoDTO)
                && !ObjectUtils.isEmpty(carInfoDTO.getCarGpsApplyDto())){
            CarGpsApply carGpsApply = carGpsApplyService.getOne(Wrappers.<CarGpsApply>query().lambda()
                    .eq(CarGpsApply::getApplyNo,carInfoDTO.getApplyNo())
                    .eq(CarGpsApply::getContractNo,carInfoDTO.getContractNo())
                    .eq(CarGpsApply::getCarId,carInfoDTO.getCarId()));
            if(ObjectUtils.isEmpty(carGpsApply)){
                carGpsApply = new CarGpsApply();
            }
            CarGpsApplyDTO carGpsApplyDto = carInfoDTO.getCarGpsApplyDto();
            BeanUtil.copyProperties(carGpsApplyDto,carGpsApply, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            carGpsApply.setContractNo(carInfoDTO.getContractNo());
            carGpsApply.setCarId(carInfoDTO.getCarId());
            carGpsApply.setCarVin(carInfoDTO.getCarVin());
            if(carGpsApply.getOrderNo()!=null&&carGpsApply.getOrderNo()!=""){
                carGpsApply.setApplyStatus(AfsEnumUtil.key(GpsStatusEnum.FIRST_TRIAL));
            }
            carGpsApplyService.saveOrUpdate(carGpsApply);
            log.info("申请编号：{}=>合同号码：{}=>车辆编号：{}=>gps申请信息保存成功！",carInfoDTO.getApplyNo(), carInfoDTO.getContractNo(), carInfoDTO.getCarId());
        }

        return null;
    }
    /**解析银行卡信息*/
    private LoanBankCardInfo parseLoanBankCardInfo(LoanBankCardInfoDTO loanBankCardInfoDto,String contractNo,String applyNo,CaseMqAcceptRecord caseMqAcceptRecord){
        if(!ObjectUtils.isEmpty(loanBankCardInfoDto)){
            LoanBankCardInfo loanBankCardInfo=loanBankCardInfoService.getOne(Wrappers.<LoanBankCardInfo>query().lambda()
                    .eq(LoanBankCardInfo::getApplyNo,applyNo)
                    .eq(LoanBankCardInfo::getContractNo,contractNo));
            LoanBankCardInfo original=loanBankCardInfoService.getOne(Wrappers.<LoanBankCardInfo>query().lambda()
                    .eq(LoanBankCardInfo::getApplyNo,applyNo)
                    .eq(LoanBankCardInfo::getContractNo,contractNo));
            if(ObjectUtils.isEmpty(loanBankCardInfo)){
                loanBankCardInfo=new LoanBankCardInfo();
            }
            BeanUtil.copyProperties(loanBankCardInfoDto,loanBankCardInfo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            LoanBankCardInfo target=loanBankCardInfo;
            caseMqCompareInfoService.saveInfo(CompareEntity.builder()
                    .acceptId(caseMqAcceptRecord.getId())
                    .applyNo(applyNo)
                    .contractNo(contractNo)
                    .entityClass("LoanBankCardInfo")
                    .original(original==null?new LoanBankCardInfo():original)
                    .target(target)
                    .version(caseMqAcceptRecord.getVersion())
                    .dataId(String.valueOf(target.getId()))
                    .build());
            /*auditLogService.saveAuditLog(AuditLogWrapper.builder()
                    .oldObject(original)
                    .newObject(target)
                    .changeReason("return")
                    .currentUserName("system")
                    .changeIndex(caseMqAcceptRecord.getId().toString())
                    .build());*/
            loanBankCardInfoService.saveOrUpdate(loanBankCardInfo);
            log.error("申请编号：{}=>合同号码：{}=>银行卡信息保存成功",applyNo, contractNo);
        }else{
            log.error("申请编号：{}=>合同号码：{}=>银行卡输入对象为空",applyNo, contractNo);
        }

        return null;
    }

    /**解析影像件信息*/
    private ResultDTO parseAttachmentFileList(ArrayList<AttachmentDTO> attachmentDtoList, String  contractNo, String applyNo){
        if(!CollectionUtils.isEmpty(attachmentDtoList)){
            List<ComAttachmentFile> list =new ArrayList<>();
            attachmentDtoList.forEach(attachmentDTO->{
                ComAttachmentFile comFile=comAttachmentFileService.getById(attachmentDTO.getId());
                if(ObjectUtils.isEmpty(comFile)){
                    comFile=new ComAttachmentFile();
                }
                BeanUtil.copyProperties(attachmentDTO,comFile, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                list.add(comFile);
            });
            comAttachmentFileService.saveOrUpdateBatch(list);
        }else{
            log.info("申请编号：{}=>合同号码：{}=>影像件信息集合为空！",applyNo, contractNo);
        }
        return null;
    }
}
